package top.chaileilei.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;

/**
 * @Description 使用Curator实现分布式计数器
 * @Time 2019/2/12
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class DistAtomicInt {
    private static String path = "/dhghr";
    private static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("119.27.189.174:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();


    public static void main(String[] args) throws Exception {
        distAtomicInt();
    }

    public static void distAtomicInt() throws Exception {
        client.start();
        DistributedAtomicInteger atomicInteger =
                new DistributedAtomicInteger( client, path,
                        new RetryNTimes( 3, 1000 ) );
        AtomicValue<Integer> rc = atomicInteger.add( 8 );
        Integer integer = rc.postValue();
        Integer integer1 = rc.preValue();
        System.out.println(integer);
        System.out.println(integer1);
        System.out.println( "Result: " + rc.succeeded() );
    }
}
